package com.hbpu.encap.socket.homework;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Homework03Client {
    public static void main(String[] args) {
        try (Socket socket = new Socket(InetAddress.getLocalHost(), 8888)) {
            try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
                System.out.print("请输入你要下载的音乐文件的全名：");
                String next = new Scanner(System.in).next();
                bufferedWriter.write(next);
                bufferedWriter.newLine();
                bufferedWriter.flush();
                System.out.println("下载请求已发送！");
                try (DataInputStream bufferedInputStream = new DataInputStream(socket.getInputStream())) {
                    try (DataOutputStream bufferedOutputStream = new DataOutputStream(new FileOutputStream("E:\\load\\" + next))) {
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = bufferedInputStream.read(buffer)) != -1) {
                            bufferedOutputStream.write(buffer, 0, len);
                        }         
                        bufferedOutputStream.flush();

                        System.out.println("文件下载成功！");

                        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                            String s = bufferedReader.readLine();
                            System.out.println(s);
                            new Scanner(System.in).nextLine();
                        } catch (IOException e) {
                            System.out.println("服务器回复接收失败！" + e.getMessage());
                        }
                    } catch (IOException e) {
                        System.out.println("文件下载失败" + e.getMessage());
                    }
                } catch (IOException e) {
                    System.out.println("文件接受失败" + e.getMessage());
                }

            } catch (IOException e) {
                System.out.println("请求发送错误" + e.getMessage());
            }
        } catch (IOException e) {
            System.out.println("在请求连接时出现异常" + e.getMessage());
        }
    }
}
